//
//  AddMessageViewController.m
//  YinHang
//
//  Created by idea on 14-9-18.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "AddMessageViewController.h"

@interface AddMessageViewController ()<ASIHTTPRequestDelegate>{
    /* 提交发布信息请求 */
    ASIFormDataRequest *postInfoRequest;
    MBProgressHUD *postHud;
    
    __weak IBOutlet UIScrollView *ScrollView;
    NSString *contentStr;
    //参数
    NSString *action;
    NSDictionary *paramsDict;
}

@end

@implementation AddMessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    contentStr = @"";
    [self postInformation];
    //scrollView
    ScrollView.bounces = NO;
    ScrollView.scrollEnabled = YES;
    ScrollView.alwaysBounceHorizontal = YES;
    ScrollView.frame = IPHONE5 ? CGRectMake(0, 0, 320, 568) :CGRectMake(0, 0, 320, 480);
    ScrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 568);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = _navTitle;
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    _isAdd = YES;//默认增加
    _messageContent.bounces = YES;
    _messageContent.layer.borderColor = UIColor.grayColor.CGColor;
    _messageContent.layer.borderWidth = 1;
    [_messageContent.layer setCornerRadius:5];//设置圆角
    
    
    [self addOrAlter];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Custom Method

//收起键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self textViewResignFirst];
}
-(void)textViewResignFirst{
    [_messageTitle resignFirstResponder];
    [_messageContent resignFirstResponder];
}
//添加或修改
-(void)addOrAlter{
    if ([_navTitle isEqualToString:@"留言详情"]) {
        _isAdd = NO;
        _messageTitle.text = _messageTitle_;
        _messageContent.text = contentStr;
        _messageAuthor.text = _messageAuthor_;
        _laddrTextField.text = _laddr;
        _ltelTextField.text = _ltel;
        _lemailTextField.text = _lemail;
        
    }else{
        
    }
}
/* 提交发布信息请求 */
- (void)postInformation {
    
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在查询，请稍后...";
        }
        
        postInfoRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postInfoRequest.requestMethod = @"POST";
        // 设置超时时间
        postInfoRequest.timeOutSeconds = 60;
        postInfoRequest.delegate = self;
        // 设置参数
        action = @"liuyanmain";
        paramsDict = @{@"lid":_lid};//lid名;
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postInfoRequest.postBody = [paramsData mutableCopy];
        
        [postInfoRequest startAsynchronous];
    }
}
#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            postHud.hidden = YES;
            NSDictionary *content = result[@"info"];
            contentStr = content[@"LContent"];
            _messageContent.text = contentStr;
            //[SVProgressHUD showSuccessWithStatus:@"删除成功"];
            
        } else {
            postHud.hidden = YES;
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        postHud.hidden = YES;
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    postHud.hidden = YES;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


/*
//提交
- (IBAction)commit:(id)sender {
    if (_isAdd) {
        [_delegate addMessageWithName:_messageTitle.text MessageContent:_messageContent.text];
    }else{
        [_delegate alterMessageAtRow:_selectRow withMessageTitle:_messageTitle.text MessageContent:_messageContent.text];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
*/
//返回
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)dealloc{
    postInfoRequest = nil;
    postHud = nil;
}
@end
